import { useState, useEffect, useRef } from "react";
import { Button, Modal, Form } from "antd";
import { CloseOutlined } from "@ant-design/icons";
import styles from "./index.less";
import { getOrgStaff } from "./service";
import Tree from "./Tree";

const OrgStaff = (props: { multiple: boolean, onSelectChange: Function }) => {
  const treeRef = useRef();
  const [visible, setVisible] = useState(false);
  const [orgTree, setOrgtree] = useState<any[]>([]);
  const [deleteKeys, setDeleteKeys] = useState<any[]>([]);
  const [checkedInfo, setCheckedInfo] = useState<{ key: number, title: string, label: string }[]>([]);
  const [okSelected, setOkSelected] = useState<any[]>([]);

  const _getOrgStaff = async () => {
    const res = await getOrgStaff();
    let formatRes = JSON.stringify(res.data);
    formatRes = formatRes.replaceAll('orgId', 'key')
      .replaceAll('orgName', 'title')
      .replaceAll('subList', 'children');
    setOrgtree([JSON.parse(formatRes)])
  }
  useEffect(() => {
    _getOrgStaff()
  }, [])
  useEffect(() => {
    if (visible) {
      setCheckedInfo(okSelected);
    }
  }, [visible])
  return (
    <div>
      {!okSelected.length ? <Button type="dashed" onClick={() => setVisible(true)}>
        部门列表
      </Button> :
        <div onClick={() => setVisible(true)} className={styles.showItem}>
          {
            okSelected.map(item => (
              <div key={item.key} className={styles.selectItem}>
                <div className={styles.avatar}>{item.label[0]}</div>
                {item.label}
              </div>
            ))
          }
        </div>}
      <Modal
        title="组织机构"
        visible={visible}
        maskClosable={false}
        onCancel={() => {
          setCheckedInfo([]);
          setVisible(false)
        }}
        destroyOnClose
        onOk={() => {
          // const data = (treeRef.current as any).onOk();
          console.log(checkedInfo)
          props.onSelectChange(checkedInfo);
          setOkSelected(checkedInfo);
          setVisible(false);
        }}
      >
        <div className={styles.selected}>
          {
            checkedInfo.map(item => (
              <div key={item.key} className={styles.selectItem}>
                <div className={styles.avatar}>{item.label[0]}</div>
                {item.label}
                <CloseOutlined className={styles.closeBtn} onClick={() => {
                  setDeleteKeys([item.key]);
                  setCheckedInfo(checkedInfo.filter(n => {
                    return n.key !== item.key
                  }));
                }} />
              </div>
            ))
          }
        </div>
        <Tree
          ref={treeRef}
          data={orgTree}
          initData={okSelected}
          multiple={props.multiple}
          onSelect={(data) => {
            setCheckedInfo(data)
          }}
          deleteKeys={deleteKeys}
        />
      </Modal>
    </div>
  )
}

export default OrgStaff;
